import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';
import modelCacheManager from '../model-library/ModelCacheManager.js';
import { fixModelEncoding } from '../utils/encodingFixer.js';

// 模型加载器模块 - 专门处理3D模型加载逻辑
export class ModelLoader {
    constructor() {
        this.gltfLoader = new GLTFLoader();
        this.fbxLoader = new FBXLoader();
        this.modelsCache = new Map(); // 模型缓存 (已废弃，使用 ModelCacheManager)
        this.cacheManager = modelCacheManager; // 使用全局缓存管理器
    }

    /**
     * 根据模型ID加载模型（用于场景树加载）
     * @param {string} modelId - 模型ID
     * @param {boolean} useCache - 是否使用缓存（默认true）
     * @param {string} modelType - 模型类型（'model' 或 'node'，默认 'model'）
     * @param {Function} onProgress - 下载进度回调 (xhr)
     * @returns {Promise<THREE.Object3D>} - 返回加载的3D对象
     */
    async loadModelById(modelId, useCache = true, modelType = 'model', onProgress = null) {
        try {
            // 🎯 优先从缓存获取
            if (useCache && this.cacheManager.isModelLoaded(modelId)) {
                const cachedModel = this.cacheManager.getModelFromCache(modelId);
                
                // ✅ 修复：从缓存获取时不要重新应用材质设置！
                // 材质已经在首次加载时应用过了，再次应用会破坏材质
                // 注释原因：
                // - 第一次加载时，applyMaterialSettings 已经在第128行被调用
                // - 缓存中存储的是已经应用过材质的模型
                // - 克隆时会正确复制材质属性（通过 ModelCacheManager.cloneMaterialWithProperties）
                // - 节点的 mesh 材质绑定会在 SceneTreeManager.applyMeshMaterials 中单独应用
                
                // ❌ 移除这段代码，避免重复应用材质：
                // const currentProject = window.projectManager?.getCurrentProject();
                // const projectId = currentProject?.id;
                // if (projectId) {
                //     await this.applyMaterialSettings(cachedModel, projectId, modelId);
                // }
                
                // 如果从缓存获取，立即报告100%进度
                if (onProgress) {
                    onProgress({ loaded: 1, total: 1 });
                }
                
                return cachedModel;
            }
            
            // 如果正在加载，等待加载完成
            if (useCache && this.cacheManager.isModelLoading(modelId)) {
                return await this.cacheManager.waitForModel(modelId);
            }
            
            // 从服务器获取模型信息
            const currentProject = window.projectManager?.getCurrentProject();
            const projectId = currentProject?.id;
            if (!projectId) {
                console.error(`❌ [ModelLoader] 无法获取项目ID`);
                console.error(`   - window.projectManager:`, window.projectManager);
                console.error(`   - currentProject:`, currentProject);
                throw new Error('当前项目不存在');
            }
            
            // 🎯 添加 type 参数以支持节点模型
            let typeParam = modelType === 'node' ? '?type=node' : '';
            let response = await fetch(`/api/projects/${projectId}/models/${modelId}${typeParam}`);
            
            // 🎯 智能回退：如果是404且没有指定类型，尝试作为节点模型加载
            if (!response.ok && response.status === 404 && modelType === 'model') {
                console.warn(`⚠️ 模型未找到，尝试作为节点模型加载: ${modelId}`);
                typeParam = '?type=node';
                response = await fetch(`/api/projects/${projectId}/models/${modelId}${typeParam}`);
            }
            
            if (!response.ok) {
                throw new Error(`获取模型信息失败: ${response.status}`);
            }
            
            const result = await response.json();
            if (!result || !result.success || !result.data) {
                console.error(`   - 返回数据格式错误:`, result);
                throw new Error('模型信息无效');
            }
            
            const modelInfo = result.data;
            if (!modelInfo.filename) {
                console.error(`   - modelInfo 没有 filename 字段`);
                throw new Error('模型信息缺少 filename 字段');
            }
            
            // 构建模型文件路径 - 🎯 添加 type 参数
            const modelPath = `/api/projects/${projectId}/models/${modelId}/file${typeParam}`;
            // 根据文件扩展名选择合适的加载器
            const extension = modelInfo.filename.toLowerCase().split('.').pop();
            // 创建加载Promise并注册到缓存管理器
            const loadingPromise = (async () => {
                let object3D;
                if (extension === 'fbx') {
                    object3D = await this.loadFBX(modelPath, onProgress);
                } else if (extension === 'gltf' || extension === 'glb') {
                    object3D = await this.loadGLTF(modelPath, onProgress);
                } else {
                    throw new Error(`不支持的模型格式: ${extension}`);
                }
                return object3D;
            })();
            
            // 如果使用缓存，标记为加载中
            if (useCache) {
                this.cacheManager.setLoading(modelId, loadingPromise);
            }
            
            let object3D;
            try {
                object3D = await loadingPromise;
            } catch (error) {
                if (useCache) {
                    this.cacheManager.setError(modelId, error);
                }
                throw error;
            }
            // ✅ 设置导入缩放系数（Import Scale）
            // FBX通常使用厘米单位，需要转换为米（×0.01）
            // glTF/GLB已是米单位，保持1.0
            let importScale = 1.0;
            if (extension === 'fbx') {
                importScale = 0.01;
            } else {
            }
            
            // 保存导入缩放到 userData（只在导入时设置一次，之后不变）
            object3D.userData.importScale = importScale;
            object3D.userData.fileType = extension;
            // ✅ 标记此对象所属的模型ID（用于区分父子节点）
            // 标记根对象和所有子对象，确保整个模型树都有正确的 modelId
            object3D.userData.modelId = modelId;
            object3D.traverse((child) => {
                if (!child.userData) {
                    child.userData = {};
                }
                child.userData.modelId = modelId;
            });
            
            // 应用物理缩放（importScale × userScale，初始userScale=1）
            object3D.scale.setScalar(importScale);
            
            // 🎨 应用保存的原始材质属性（新增！）
            // 这会从模型配置的 meshMaterials 中读取并恢复材质属性
            await this.applyOriginalMaterialProperties(object3D, projectId, modelId, modelType);
            
            // 🎨 应用材质设置（仅当有 materialId 配置时）
            // 这里会自动应用保存的深度控制参数（polygonOffset等）
            await this.applyMaterialSettings(object3D, projectId, modelId, modelType);
            
            // 📦 添加到缓存（存储原始模型，不是克隆）
            if (useCache) {
                this.cacheManager.addToCache(modelId, object3D, {
                    name: modelInfo.name,
                    filename: modelInfo.filename,
                    format: extension,
                    path: modelInfo.path
                });
                
                // ⭐ 返回保留UUID的克隆，确保首次加载和后续加载UUID一致
                const clonedModel = this.cacheManager.getModelFromCache(modelId);
                return clonedModel;
            }
            return object3D;
            
        } catch (error) {
            console.error(`❌ 加载模型失败 (${modelId}):`, error);
            throw error;
        }
    }
    
    /**
     * 加载FBX模型
     * @param {string} path - 模型路径
     * @param {Function} onProgress - 进度回调函数(xhr)
     */
    loadFBX(path, onProgress = null) {
        return new Promise((resolve, reject) => {
            this.fbxLoader.load(
                path,
                (object) => {
                    // 🎯 立即修复FBX模型中的编码问题
                    fixModelEncoding(object);
                    resolve(object);
                },
                onProgress,
                (error) => reject(error)
            );
        });
    }
    
    /**
     * 加载GLTF/GLB模型
     * @param {string} path - 模型路径
     * @param {Function} onProgress - 进度回调函数(xhr)
     */
    loadGLTF(path, onProgress = null) {
        return new Promise((resolve, reject) => {
            this.gltfLoader.load(
                path,
                (gltf) => {
                    // 🎯 立即修复GLTF模型中的编码问题
                    fixModelEncoding(gltf.scene);
                    resolve(gltf.scene);
                },
                onProgress,
                (error) => reject(error)
            );
        });
    }

    /**
     * 应用保存的原始材质属性
     * @param {THREE.Object3D} object3D - 3D对象
     * @param {string} projectId - 项目ID
     * @param {string} modelId - 模型ID
     * @param {string} modelType - 模型类型（'model' 或 'node'）
     */
    async applyOriginalMaterialProperties(object3D, projectId, modelId, modelType = 'model') {
        try {
            // 获取模型信息（包含 meshMaterials）
            const typeParam = modelType === 'node' ? '?type=node' : '';
            const modelResponse = await fetch(`/api/projects/${projectId}/models/${modelId}${typeParam}`);
            if (!modelResponse.ok) return;
            
            const modelResult = await modelResponse.json();
            if (!modelResult.success || !modelResult.data) return;
            
            const modelInfo = modelResult.data;
            const meshMaterials = modelInfo.meshMaterials || {};
            
            // 如果没有保存的材质信息，跳过
            if (Object.keys(meshMaterials).length === 0) {
                return;
            }
            
            // 遍历模型中的所有mesh，应用保存的材质属性
            object3D.traverse((child) => {
                if (child.isMesh && child.material) {
                    const meshName = child.name;
                    const meshData = meshMaterials[meshName];
                    
                    // 如果找到对应的材质配置且有 properties 字段
                    if (meshData && meshData.properties) {
                        const props = meshData.properties;
                        const material = child.material;
                        
                        // 应用基础颜色
                        if (props.color && material.color) {
                            material.color.set(props.color);
                        }
                        
                        // 应用 PBR 属性
                        if (props.metalness !== undefined && material.metalness !== undefined) {
                            material.metalness = props.metalness;
                        }
                        if (props.roughness !== undefined && material.roughness !== undefined) {
                            material.roughness = props.roughness;
                        }
                        
                        // 应用发光属性
                        if (props.emissive && material.emissive) {
                            material.emissive.set(props.emissive);
                        }
                        if (props.emissiveIntensity !== undefined && material.emissiveIntensity !== undefined) {
                            material.emissiveIntensity = props.emissiveIntensity;
                        }
                        
                        // 应用高光属性（Phong材质）
                        if (props.specular && material.specular) {
                            material.specular.set(props.specular);
                        }
                        if (props.shininess !== undefined && material.shininess !== undefined) {
                            material.shininess = props.shininess;
                        }
                        
                        // 应用透明度
                        if (props.opacity !== undefined) {
                            material.opacity = props.opacity;
                        }
                        if (props.transparent !== undefined) {
                            material.transparent = props.transparent;
                        }
                        
                        // 应用双面渲染
                        if (props.side !== undefined) {
                            material.side = props.side;
                        }
                        
                        // 应用其他属性
                        if (props.aoMapIntensity !== undefined && material.aoMapIntensity !== undefined) {
                            material.aoMapIntensity = props.aoMapIntensity;
                        }
                        if (props.bumpScale !== undefined && material.bumpScale !== undefined) {
                            material.bumpScale = props.bumpScale;
                        }
                        if (props.normalScale && material.normalScale) {
                            material.normalScale.set(props.normalScale.x, props.normalScale.y);
                        }
                        if (props.flatShading !== undefined) {
                            material.flatShading = props.flatShading;
                        }
                        if (props.wireframe !== undefined) {
                            material.wireframe = props.wireframe;
                        }
                        if (props.vertexColors !== undefined) {
                            material.vertexColors = props.vertexColors;
                        }
                        
                        // 标记材质需要更新
                        material.needsUpdate = true;
                    }
                }
            });
            
        } catch (error) {
            console.warn(`⚠️ [ModelLoader] 应用原始材质属性失败:`, error);
            // 失败不影响模型加载
        }
    }
    
    /**
     * 应用材质设置
     * @param {THREE.Object3D} object3D - 3D对象
     * @param {string} projectId - 项目ID
     * @param {string} modelId - 模型ID
     * @param {string} modelType - 模型类型（'model' 或 'node'）
     */
    async applyMaterialSettings(object3D, projectId, modelId, modelType = 'model') {
        try {
            // 首先获取模型信息，查看是否有材质ID引用
            const typeParam = modelType === 'node' ? '?type=node' : '';
            const modelResponse = await fetch(`/api/projects/${projectId}/models/${modelId}${typeParam}`);
            
            if (!modelResponse.ok) {
                return;
            }
            
            const modelResult = await modelResponse.json();
            
            if (!modelResult.success || !modelResult.data) {
                return;
            }
            
            const modelInfo = modelResult.data;
            let materialSettings = null;
            
            // 如果模型有材质ID引用，从材质库加载
            if (modelInfo.materialId) {
                const materialResponse = await fetch(`/api/projects/${projectId}/materials/${modelInfo.materialId}`);
                
                if (materialResponse.ok) {
                    const materialResult = await materialResponse.json();
                    if (materialResult.success && materialResult.data) {
                        materialSettings = materialResult.data;
                    }
                }
            }
            
            // 如果没有材质ID或加载失败，尝试从旧的material字段加载
            if (!materialSettings && modelInfo.material) {
                materialSettings = modelInfo.material;
            }
            
            if (!materialSettings) {
                return;
            }
            // 纹理加载器
            const textureLoader = new THREE.TextureLoader();
            
            // ✅ 辅助函数：检查对象是否属于不同的模型
            // 遍历对象的祖先链，如果发现任何祖先有不同的 modelId，返回 true
            const belongsToDifferentModel = (obj) => {
                let current = obj;
                while (current && current !== object3D) {
                    if (current.userData && current.userData.modelId && current.userData.modelId !== modelId) {
                        return true; // 发现不同的 modelId
                    }
                    current = current.parent;
                }
                return false; // 没有发现不同的 modelId
            };
            
            // ✅ 使用自定义递归函数遍历，可以正确跳过子模型的整个子树
            const traverseAndApplyMaterial = async (obj, depth = 0) => {
                const indent = '  '.repeat(depth);
                
                // 检查当前对象或其祖先是否属于不同的模型
                if (obj !== object3D && belongsToDifferentModel(obj)) {
                    const objModelId = obj.userData?.modelId || '(继承自祖先)';
                    return; // 不再递归到这个子树
                }
                
                if (obj.isMesh) {
                }
                
                // 如果是网格对象，应用材质
                if (obj.isMesh) {
                    const material = obj.material;
                    
                    // 如果是数组材质（多材质），遍历所有材质
                    const materials = Array.isArray(material) ? material : [material];
                    
                    // 🔑 追踪是否有透明材质
                    let hasTransparentMaterial = false;
                    
                    for (let index = 0; index < materials.length; index++) {
                        const mat = materials[index];
                        if (!mat) continue;
                        // 获取目标材质类型
                        const targetMaterialType = materialSettings.materialType || 'MeshStandardMaterial';
                        // 保存原有贴图
                        const originalTextures = {
                            map: mat.map,
                            normalMap: mat.normalMap,
                            bumpMap: mat.bumpMap,
                            aoMap: mat.aoMap,
                            emissiveMap: mat.emissiveMap,
                            metalnessMap: mat.metalnessMap,
                            roughnessMap: mat.roughnessMap,
                            specularMap: mat.specularMap
                        };
                        
                        // ✅ 检查材质是否已经属于当前模型
                        // 如果材质没有 modelId 标记，或者标记与当前模型不同，则需要克隆
                        const matModelId = mat.userData?.modelId;
                        const needsClone = !matModelId || matModelId !== modelId;
                        
                        let targetMat = mat;
                        
                        if (needsClone) {
                            // 克隆材质以避免共享
                            targetMat = mat.clone();
                            targetMat.userData = { ...mat.userData };
                            targetMat.userData.modelId = modelId; // 标记材质属于当前模型
                            
                            // 替换材质
                            if (Array.isArray(obj.material)) {
                                obj.material[index] = targetMat;
                            } else {
                                obj.material = targetMat;
                            }
                        } else {
                        }
                        
                        // ✅ 如果材质类型不匹配，创建新的材质类型
                        if (targetMat.type !== targetMaterialType) {
                            const newMat = this.createMaterialByType(targetMaterialType, targetMat);
                            newMat.userData.modelId = modelId; // 标记新材质
                            
                            // 恢复原有贴图到新材质
                            Object.keys(originalTextures).forEach(key => {
                                if (originalTextures[key] && newMat[key] !== undefined) {
                                    newMat[key] = originalTextures[key];
                                }
                            });
                            
                            // 替换材质
                            if (Array.isArray(obj.material)) {
                                obj.material[index] = newMat;
                            } else {
                                obj.material = newMat;
                            }
                            
                            // 应用材质设置到新材质（传入原贴图以保留）
                            await this.applyMaterialProps(newMat, materialSettings, textureLoader, originalTextures);
                        } else {
                            // 材质类型匹配，应用属性（传入原贴图以保留）
                            await this.applyMaterialProps(targetMat, materialSettings, textureLoader, originalTextures);
                        }
                        
                        // 🔑 检查材质是否为透明材质
                        if (mat.transparent || mat.alphaMap || mat.alphaTest > 0 || mat.userData.needsRenderOrder) {
                            hasTransparentMaterial = true;
                        }
                    }
                    
                    // 🔑 关键修复：如果有透明材质，设置mesh的renderOrder
                    if (hasTransparentMaterial) {
                        // 根据物体类型和位置设置不同的renderOrder
                        const meshName = (obj.name || '').toLowerCase();
                        
                        if (meshName.includes('road') || meshName.includes('line') || meshName.includes('马路') || meshName.includes('线')) {
                            // 马路线等贴地透明物体
                            obj.renderOrder = 100;
                            console.log(`   🛣️ 马路线透明材质设置 renderOrder=100: ${obj.name || '(unnamed)'}`);
                        } else if (obj.position.y < 0.1) {
                            // 接近地面的透明物体
                            obj.renderOrder = 200;
                            console.log(`   🏠 地面透明材质设置 renderOrder=200: ${obj.name || '(unnamed)'}`);
                        } else {
                            // 其他透明物体
                            obj.renderOrder = 999;
                            console.log(`   🌿 空中透明材质设置 renderOrder=999: ${obj.name || '(unnamed)'}`);
                        }
                    }
                }
                
                // 递归处理子对象
                if (obj.children && obj.children.length > 0) {
                    for (const child of obj.children) {
                        await traverseAndApplyMaterial(child, depth + 1);
                    }
                }
            };
            
            // 开始遍历
            await traverseAndApplyMaterial(object3D);
        } catch (error) {
            console.warn(`⚠️ [ModelLoader] 应用材质设置失败:`, error);
            // 材质应用失败不影响模型加载，只记录警告
        }
    }
    
    /**
     * 根据类型创建材质
     * @param {string} materialType - 材质类型
     * @param {THREE.Material} sourceMat - 源材质（用于复制属性）
     * @returns {THREE.Material} 新材质
     */
    createMaterialByType(materialType, sourceMat) {
        const baseProps = {
            color: sourceMat.color ? sourceMat.color.clone() : new THREE.Color(0xffffff),
            map: sourceMat.map || null,
            opacity: sourceMat.opacity !== undefined ? sourceMat.opacity : 1.0,
            // 🔧 修复：如果有贴图或原材质是透明的，都需要开启transparent
            transparent: sourceMat.transparent || !!sourceMat.map || !!sourceMat.alphaMap || sourceMat.opacity < 1.0,
            side: sourceMat.side !== undefined ? sourceMat.side : THREE.FrontSide
        };
        
        let newMat;
        
        switch(materialType) {
            case 'MeshStandardMaterial':
                newMat = new THREE.MeshStandardMaterial({
                    ...baseProps,
                    normalMap: sourceMat.normalMap || null,
                    emissive: sourceMat.emissive ? sourceMat.emissive.clone() : new THREE.Color(0x000000),
                    emissiveIntensity: sourceMat.emissiveIntensity || 0,
                    emissiveMap: sourceMat.emissiveMap || null,
                    metalness: 0.5,
                    roughness: 0.5
                });
                break;
                
            case 'MeshPhongMaterial':
                newMat = new THREE.MeshPhongMaterial({
                    ...baseProps,
                    emissive: sourceMat.emissive ? sourceMat.emissive.clone() : new THREE.Color(0x000000),
                    emissiveIntensity: sourceMat.emissiveIntensity || 0,
                    specular: new THREE.Color(0x111111),
                    shininess: 30
                });
                break;
                
            case 'MeshLambertMaterial':
                newMat = new THREE.MeshLambertMaterial({
                    ...baseProps,
                    emissive: sourceMat.emissive ? sourceMat.emissive.clone() : new THREE.Color(0x000000),
                    emissiveIntensity: sourceMat.emissiveIntensity || 0
                });
                break;
                
            case 'MeshBasicMaterial':
                newMat = new THREE.MeshBasicMaterial({
                    ...baseProps
                });
                break;
                
            case 'MeshPhysicalMaterial':
                newMat = new THREE.MeshPhysicalMaterial({
                    ...baseProps,
                    normalMap: sourceMat.normalMap || null,
                    emissive: sourceMat.emissive ? sourceMat.emissive.clone() : new THREE.Color(0x000000),
                    emissiveIntensity: sourceMat.emissiveIntensity || 0,
                    emissiveMap: sourceMat.emissiveMap || null,
                    metalness: 0.5,
                    roughness: 0.5,
                    clearcoat: 0,
                    clearcoatRoughness: 0
                });
                break;
                
            default:
                console.warn(`未知材质类型: ${materialType}，使用 MeshStandardMaterial`);
                newMat = new THREE.MeshStandardMaterial(baseProps);
        }
        return newMat;
    }
    
    /**
     * 应用材质属性
     * @param {THREE.Material} material - 材质对象
     * @param {Object} settings - 材质设置
     * @param {THREE.TextureLoader} textureLoader - 纹理加载器
     */
    async applyMaterialProps(material, settings, textureLoader, originalTextures = null) {
        // ⚠️ 检查材质类型：metalness/roughness 只在 PBR 材质中有效
        const isPBRMaterial = material.type === 'MeshStandardMaterial' || 
                             material.type === 'MeshPhysicalMaterial';
        
        if (!isPBRMaterial) {
            console.warn(`   ⚠️ 材质类型 ${material.type} 不支持 PBR 属性（metalness/roughness）`);
            console.warn(`   → 建议：转换为 MeshStandardMaterial 以支持完整的材质编辑功能`);
        }
        
        // 基础颜色
        if (settings.color) {
            material.color.set(settings.color);
        }
        
        // 金属度（仅 PBR 材质）
        if (settings.metalness !== undefined && material.metalness !== undefined) {
            material.metalness = settings.metalness;
        }
        
        // 粗糙度（仅 PBR 材质）
        if (settings.roughness !== undefined && material.roughness !== undefined) {
            material.roughness = settings.roughness;
        }
        
        // 自发光
        if (settings.emissive && material.emissive) {
            material.emissive.set(settings.emissive);
        }
        if (settings.emissiveIntensity !== undefined && material.emissiveIntensity !== undefined) {
            material.emissiveIntensity = settings.emissiveIntensity;
        }
        
        // 透明度
        if (settings.opacity !== undefined) {
            material.opacity = settings.opacity;
            // 🔧 修复：如果有贴图或opacity<1，都需要开启transparent
            material.transparent = settings.opacity < 1.0 || !!material.map || !!material.alphaMap;
        }
        
        // 🎯 透明度控制参数（解决透明贴图遮挡问题）
        if (settings.alphaTest !== undefined) {
            material.alphaTest = settings.alphaTest;
        }
        
        // 🎯 深度写入控制（关键！解决透明区域遮挡后面物体的问题）
        if (settings.depthWrite !== undefined) {
            material.depthWrite = settings.depthWrite;
        }
        
        // AO强度（需要检查是否支持）
        if (settings.aoIntensity !== undefined && material.aoMapIntensity !== undefined) {
            material.aoMapIntensity = settings.aoIntensity;
        }
        
        // 凹凸强度（需要检查是否支持）
        if (settings.bumpScale !== undefined && material.bumpScale !== undefined) {
            material.bumpScale = settings.bumpScale;
        }
        
        // 双面渲染
        if (settings.doubleSided !== undefined) {
            material.side = settings.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
        }
        
        // 恢复原有贴图（如果有）
        // 这样可以保留FBX文件中嵌入的贴图，不会被覆盖
        if (originalTextures) {
            if (originalTextures.map && !material.map) {
                material.map = originalTextures.map;
            }
            if (originalTextures.normalMap && !material.normalMap) {
                material.normalMap = originalTextures.normalMap;
            }
            if (originalTextures.bumpMap && !material.bumpMap) {
                material.bumpMap = originalTextures.bumpMap;
            }
            if (originalTextures.aoMap && !material.aoMap) {
                material.aoMap = originalTextures.aoMap;
            }
            if (originalTextures.emissiveMap && !material.emissiveMap) {
                material.emissiveMap = originalTextures.emissiveMap;
            }
            if (originalTextures.metalnessMap && !material.metalnessMap) {
                material.metalnessMap = originalTextures.metalnessMap;
            }
            if (originalTextures.roughnessMap && !material.roughnessMap) {
                material.roughnessMap = originalTextures.roughnessMap;
            }
            if (originalTextures.specularMap && !material.specularMap) {
                material.specularMap = originalTextures.specularMap;
            }
        }
        
        // 🎯 加载纹理贴图 - 支持路径或纹理名称
        // 获取项目ID用于查询纹理
        const currentProject = window.projectManager?.getCurrentProject();
        const projectId = currentProject?.id;
        
        // 辅助函数：通过纹理名称或ID查找纹理路径
        const getTexturePath = async (textureNameOrPath) => {
            console.log(`🔍 [纹理查找] 开始查找纹理: "${textureNameOrPath}"`);
            
            if (!textureNameOrPath) {
                console.log(`   ❌ 纹理名称为空`);
                return null;
            }
            
            // 如果已经是路径格式（以 / 开头），直接返回
            if (textureNameOrPath.startsWith('/')) {
                console.log(`   ✅ 已经是路径格式，直接返回: ${textureNameOrPath}`);
                return textureNameOrPath;
            }
            
            // 否则，假设是纹理名称，通过API查找纹理
            if (!projectId) {
                console.warn('   ⚠️ 无法获取项目ID，无法加载纹理:', textureNameOrPath);
                return null;
            }
            
            try {
                // 获取项目的所有纹理列表
                const apiUrl = `/api/projects/${projectId}/textures`;
                console.log(`   📡 请求纹理列表: ${apiUrl}`);
                
                const response = await fetch(apiUrl);
                console.log(`   📡 响应状态: ${response.status} ${response.statusText}`);
                
                if (!response.ok) {
                    console.warn(`   ❌ 获取纹理列表失败: ${response.status}`);
                    return null;
                }
                
                const result = await response.json();
                console.log(`   📦 API响应:`, result);
                
                if (!result.success || !result.data) {
                    console.warn(`   ❌ API响应格式错误`);
                    return null;
                }
                
                console.log(`   📋 纹理列表 (${result.data.length} 个):`, result.data.map(t => ({
                    id: t.id,
                    name: t.name,
                    displayName: t.displayName,
                    path: t.path
                })));
                
                // 查找匹配的纹理（通过 displayName 或 name）
                const texture = result.data.find(t => 
                    t.displayName === textureNameOrPath || 
                    t.name === textureNameOrPath ||
                    t.id === textureNameOrPath
                );
                
                if (texture && texture.id) {
                    // 使用正确的API路由：/api/projects/:id/textures/:textureId/file
                    const fullPath = `/api/projects/${projectId}/textures/${texture.id}/file`;
                    console.log(`   ✅ 找到匹配纹理:`);
                    console.log(`      - ID: ${texture.id}`);
                    console.log(`      - Name: ${texture.name}`);
                    console.log(`      - DisplayName: ${texture.displayName}`);
                    console.log(`      - Path: ${texture.path}`);
                    console.log(`      - Full URL: ${fullPath}`);
                    return fullPath;
                }
                
                console.warn(`   ❌ 未找到匹配的纹理: "${textureNameOrPath}"`);
                console.warn(`   可用的纹理名称:`, result.data.map(t => `"${t.displayName}"`).join(', '));
                return null;
            } catch (error) {
                console.error('   ❌ 查找纹理失败:', error);
                return null;
            }
        };
        
        // 🎯 辅助函数：应用UV变换到纹理
        const applyUVTransform = (texture, settings) => {
            if (!texture || !settings) return;
            
            // UV重复
            if (settings.uvRepeatX !== undefined && settings.uvRepeatY !== undefined) {
                texture.repeat.set(settings.uvRepeatX, settings.uvRepeatY);
                console.log(`   🔄 UV重复: (${settings.uvRepeatX}, ${settings.uvRepeatY})`);
            }
            
            // UV偏移
            if (settings.uvOffsetX !== undefined && settings.uvOffsetY !== undefined) {
                texture.offset.set(settings.uvOffsetX, settings.uvOffsetY);
                console.log(`   ↔️ UV偏移: (${settings.uvOffsetX}, ${settings.uvOffsetY})`);
            }
            
            // UV旋转
            if (settings.uvRotation !== undefined) {
                texture.rotation = settings.uvRotation;
                const degrees = (settings.uvRotation * 180 / Math.PI).toFixed(1);
                console.log(`   🔄 UV旋转: ${settings.uvRotation} 弧度 (${degrees}°)`);
            }
            
            // UV旋转中心点
            if (settings.uvCenterX !== undefined && settings.uvCenterY !== undefined) {
                texture.center.set(settings.uvCenterX, settings.uvCenterY);
                console.log(`   📍 UV中心点: (${settings.uvCenterX}, ${settings.uvCenterY})`);
            }
            
            texture.needsUpdate = true;
        };
        
        // 加载基础颜色贴图（map）
        if (settings.map) {
            console.log(`🎨 [贴图加载] 准备加载基础颜色贴图: "${settings.map}"`);
            const texturePath = await getTexturePath(settings.map);
            if (texturePath) {
                const fullUrl = `http://localhost:7283${texturePath}`;
                console.log(`   📥 开始加载贴图: ${fullUrl}`);
                textureLoader.load(
                    fullUrl,
                    (texture) => {
                        console.log(`   ✅ 贴图加载成功!`);
                        console.log(`      - 纹理尺寸: ${texture.image.width} x ${texture.image.height}`);
                        console.log(`      - 应用到材质:`, material);
                        texture.colorSpace = THREE.SRGBColorSpace;
                        
                        // 🔧 修复模糊问题：设置高质量纹理过滤
                        texture.generateMipmaps = true;
                        texture.minFilter = THREE.LinearMipmapLinearFilter;
                        texture.magFilter = THREE.LinearFilter;
                        const renderer = window.manager?.renderer;
                        const maxAnisotropy = renderer ? renderer.capabilities.getMaxAnisotropy() : 16;
                        texture.anisotropy = maxAnisotropy;
                        texture.needsUpdate = true;
                        
                        // 应用UV变换
                        applyUVTransform(texture, settings);
                        
                        material.map = texture;
                        material.needsUpdate = true;
                        console.log(`   ✅ 材质已更新，map已设置`);
                    },
                    undefined,
                    (error) => {
                        console.error('   ❌ 加载基础颜色贴图失败:', error);
                        console.error('      - URL:', fullUrl);
                    }
                );
            } else {
                console.warn(`   ⚠️ 无法获取纹理路径，跳过加载`);
            }
        }
        
        // 加载法线贴图（normalMap）
        if (settings.normalMap) {
            const texturePath = await getTexturePath(settings.normalMap);
            if (texturePath) {
                textureLoader.load(
                    `http://localhost:7283${texturePath}`,
                    (texture) => {
                        applyUVTransform(texture, settings);
                        material.normalMap = texture;
                        material.needsUpdate = true;
                    },
                    undefined,
                    (error) => console.warn('加载法线贴图失败:', error)
                );
            }
        }
        
        // 加载凹凸贴图（bumpMap）
        if (settings.bumpMap) {
            const texturePath = await getTexturePath(settings.bumpMap);
            if (texturePath) {
                textureLoader.load(
                    `http://localhost:7283${texturePath}`,
                    (texture) => {
                        applyUVTransform(texture, settings);
                        material.bumpMap = texture;
                        material.needsUpdate = true;
                    },
                    undefined,
                    (error) => console.warn('加载凹凸贴图失败:', error)
                );
            }
        }
        
        // 加载AO贴图（aoMap）
        if (settings.aoMap) {
            const texturePath = await getTexturePath(settings.aoMap);
            if (texturePath) {
                textureLoader.load(
                    `http://localhost:7283${texturePath}`,
                    (texture) => {
                        applyUVTransform(texture, settings);
                        material.aoMap = texture;
                        material.needsUpdate = true;
                    },
                    undefined,
                    (error) => console.warn('加载AO贴图失败:', error)
                );
            }
        }
        
        // 加载粗糙度贴图（roughnessMap）
        if (settings.roughnessMap) {
            const texturePath = await getTexturePath(settings.roughnessMap);
            if (texturePath) {
                textureLoader.load(
                    `http://localhost:7283${texturePath}`,
                    (texture) => {
                        applyUVTransform(texture, settings);
                        material.roughnessMap = texture;
                        material.needsUpdate = true;
                    },
                    undefined,
                    (error) => console.warn('加载粗糙度贴图失败:', error)
                );
            }
        }
        
        // 加载金属度贴图（metalnessMap）
        if (settings.metalnessMap) {
            const texturePath = await getTexturePath(settings.metalnessMap);
            if (texturePath) {
                textureLoader.load(
                    `http://localhost:7283${texturePath}`,
                    (texture) => {
                        applyUVTransform(texture, settings);
                        material.metalnessMap = texture;
                        material.needsUpdate = true;
                    },
                    undefined,
                    (error) => console.warn('加载金属度贴图失败:', error)
                );
            }
        }
        
        // 🎯 加载透明贴图（alphaMap）- 关键修复！
        if (settings.alphaMap) {
            console.log(`🎭 [贴图加载] 准备加载透明贴图: "${settings.alphaMap}"`);
            const texturePath = await getTexturePath(settings.alphaMap);
            if (texturePath) {
                const fullUrl = `http://localhost:7283${texturePath}`;
                console.log(`   📥 开始加载透明贴图: ${fullUrl}`);
                textureLoader.load(
                    fullUrl,
                    (texture) => {
                        console.log(`   ✅ 透明贴图加载成功!`);
                        applyUVTransform(texture, settings);
                        material.alphaMap = texture;
                        
                        // 🔧 关键设置：启用透明度
                        material.transparent = true;
                        
                        // 🔧 设置 alphaTest（如果配置中没有指定，使用默认值 0.5）
                        if (material.alphaTest === undefined || material.alphaTest === 0) {
                            material.alphaTest = 0.5;
                            console.log(`   ⚙️ 设置默认 alphaTest: 0.5`);
                        }
                        
                        // 🔧 关键：禁用深度写入，防止透明区域遮挡后面的物体
                        if (material.depthWrite === undefined) {
                            material.depthWrite = false;
                            console.log(`   ⚙️ 禁用深度写入 (depthWrite: false)`);
                        }
                        
                        material.needsUpdate = true;
                        console.log(`   ✅ 透明材质配置完成`);
                    },
                    undefined,
                    (error) => {
                        console.error('   ❌ 加载透明贴图失败:', error);
                        console.error('      - URL:', fullUrl);
                    }
                );
            } else {
                console.warn(`   ⚠️ 无法获取透明贴图路径，跳过加载`);
            }
        }
        
        // 🎯 【最终修复】自动检测并修复透明材质问题
        // 这个逻辑确保：无论何时材质被应用，都能正确处理透明度
        if (material.alphaMap || material.transparent || material.opacity < 1.0) {
            // 确保启用透明度
            if (!material.transparent) {
                material.transparent = true;
                console.log(`   🔧 [自动修复] 启用透明度: transparent = true`);
            }
            
            // 如果有 alphaMap 但没有设置 alphaTest，设置默认值
            if (material.alphaMap && (material.alphaTest === undefined || material.alphaTest === 0)) {
                material.alphaTest = settings.alphaTest || 0.5;
                console.log(`   🔧 [自动修复] 设置 alphaTest = ${material.alphaTest}`);
            }
            
            // 🔑 关键修复：确保禁用深度写入
            if (material.depthWrite !== false) {
                material.depthWrite = settings.depthWrite !== undefined ? settings.depthWrite : false;
                console.log(`   🔧 [自动修复] 禁用深度写入: depthWrite = ${material.depthWrite}`);
            }
            
            // 🔑 标记材质需要设置 renderOrder
            material.userData.needsRenderOrder = true;
        }
        
        material.needsUpdate = true;
    }

    /**
     * 旧版loadModel方法（保留向后兼容）
     */
    loadModel(path, scene, onLoad = () => {}, onError = (error) => console.error(error)) {
        this.gltfLoader.load(
            path,
            (gltf) => {
                scene.add(gltf.scene);
                onLoad(gltf);
            },
            undefined,
            (error) => {
                onError(error);
            }
        );
    }
}